package com.enniswu.weitter.user.update;

import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.enniswu.weitter.R;
import com.enniswu.weitter.base.BasePresenter;
import com.enniswu.weitter.data.local.DBSupport;
import com.enniswu.weitter.data.local.SPSupport;
import com.enniswu.weitter.data.remote.FileLoader;
import com.enniswu.weitter.data.remote.UserLoader;
import com.enniswu.weitter.entity.User;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class UpdateInfoPresenter extends BasePresenter<UpdateInfoContract.View> implements UpdateInfoContract.Presenter {

    private UserLoader uLoader;
    private FileLoader fLoader;

    public UpdateInfoPresenter(UpdateInfoContract.View view) {
        super(view);
        uLoader = new UserLoader();
        fLoader = new FileLoader();
    }

    @Override
    public void update(int id, File portrait, String name, int gender, String synopsis) {
        if (TextUtils.isEmpty(name)) {
            view.showMessage(R.string.info_no_name);
            return;
        }
        updatePortrait(id, portrait, name, gender, synopsis);
    }

    private void updatePortrait(final int id, File portrait, final String name, final int gender, final String synopsis) {
        view.showLoading();
        if (portrait == null) {
            updateInfo(id, name, gender, synopsis);
            return;
        }
        fLoader.uploadImage(id, portrait, new AbstractCallback<Object>() {
            @Override
            public void onSuccess(@Nullable Object o) {
                updateInfo(id, name, gender, synopsis);
            }
        });
    }

    private void updateInfo(final int id, String name, int gender, String synopsis) {
        uLoader.updateInfo(name, gender, synopsis, new AbstractCallback<Object>() {
            @Override
            public void onSuccess(@Nullable Object o) {
                getInfo(id);
            }
        });
    }

    private void getInfo(int id) {
        uLoader.getInfo(id, new AbstractCallback<User>() {
            @Override
            public void onSuccess(@Nullable User user) {
                if (!handleNoNullSuccess(user))
                    return;
                DBSupport.getInstance().insertOrUpdate(user);
                SPSupport.getInstance().putId(user.getId());
                EventBus.getDefault().post(user);
                view.dismissLoading();
                view.next();
            }
        });
    }
}
